package com.ptkc.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月17日
 */
@Slf4j
@Configuration
public class EsConf {

    @Value("${spring.boot.es.user}")
    private String user;

    @Value("${spring.boot.es.password}")
    private String password;

    @Value("${spring.boot.es.host}")
    private String host;

    @Value("${spring.boot.es.port}")
    private Integer port;


    @Bean
    public RestClientBuilder build() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if(user != null) {
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(user, password));
        }
        return RestClient.builder(new HttpHost(host, port))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
    }

    @Bean
    public RestClient restClient(@Autowired RestClientBuilder builder) {
        return builder.build();
    }


    @Bean
    public RestHighLevelClient highLevelClient(@Autowired RestClient client) {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(client);
        return restHighLevelClient;
    }

}
